package com.pay.service.impl;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pay.constant.Constant;
import com.pay.entity.SysRole;
import com.pay.entity.SysUser;
import com.pay.mapper.SysUserMapper;
import com.pay.service.IBaseInfoService;
import com.pay.service.ISysRoleService;
import com.pay.service.ISysUserService;
import com.pay.utils.Login;
import com.pay.utils.MD5Util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;

/**
 * <p>
 * 平台用户表 服务实现类
 * </p>
 *
 * @author Peng
 * @since 2018-12-05
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

	@Autowired
	private IBaseInfoService baseInfoService ;
	
	@Autowired
	private ISysRoleService sysRoleService ;
	
	@Override
	public SysUser checkLogin(Login login,HttpServletRequest request) {
		if(StrUtil.isBlank(login.getUsername())) {
			return null ;
		}
		if(StrUtil.isBlank(login.getPassword())) {
			return null ;
		}
		if(StrUtil.isBlank(login.getVaptcha_token())) {
			return null ;
		}
		QueryWrapper<SysUser> ew = new QueryWrapper<SysUser>();
		ew.eq("login", login.getUsername()) ;
		ew.eq("status", Constant.user_effective) ;
		SysUser user = super.getOne(ew);
		if(user == null) {
			return null ;
		}
		String md5Pass = MD5Util.md5Hex(login.getPassword()) ;
		if(!user.getPassword().equals(md5Pass)) {
			return null ;
		}
		//再查下角色是不是有效状态
		SysRole role = sysRoleService.getById(user.getRoleid());
		if(role == null) {
			//角色已不存在
			return null ;
		}
		if(role.getId() == Constant.role_invalid) {
			//角色是无效状态
			return null ;
		}
		
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("id", baseInfoService.getByKey(Constant.vaptchaVID)) ; 
		map.put("secretkey", baseInfoService.getByKey(Constant.vaptchaKEY)) ; 
		
		map.put("token", login.getVaptcha_token()) ;
		map.put("ip", request.getRemoteAddr()) ;
		String valiResult = HttpUtil.post("http://api.vaptcha.com/v2/validate", map); //验证结果
		Integer code = JSON.parseObject(valiResult).getInteger("success");
		if(code != 1) {
			return null ;
		}
		
		return user ;
	}
}
